package cs.uns.edu.ar.aygps.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import cs.uns.edu.ar.aygps.db.ConnectionFactory;
import cs.uns.edu.ar.aygps.model.Localidad;
import cs.uns.edu.ar.aygps.model.Provincia;
import cs.uns.edu.ar.aygps.model.exception.AyGPSException;

public class ProvinciaService extends ModelService {
	private static HashMap<Integer, Provincia> provincias = new HashMap<Integer, Provincia>();

	public ProvinciaService(String service) {
		super(service);
	}

	@Override
	public void executeService() throws AyGPSException {

	}

	
		
	
	public Provincia getProvinciaByName(String nombre) {
		if (provincias.isEmpty())
			loadProvincias();
		
		Iterator iter = provincias.values().iterator();
		
		while (iter.hasNext()) {
			Provincia prov = (Provincia) iter.next();
			if (prov.getName().equals(nombre))	{
				return prov;
			}
		}
		return null;		
	}

	
	private static final String FIND_PROVINCIAS = "SELECT ID, NAME FROM APP.PROVINCIA ORDER BY NAME";
	
	private void loadProvincias() {
		Connection conn;
		
		try {
			conn = ConnectionFactory.getInstance().getConnection();
			PreparedStatement ps = conn.prepareStatement(FIND_PROVINCIAS);
			
			ResultSet rs = ps.executeQuery();
			
			while (rs.next()){
				Provincia p = new Provincia();
				p.setId(rs.getInt(1));
				p.setName(rs.getString(2));
				provincias.put(new Integer(p.getId()), p);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
	}
	
	
	
	public String[]	getProvinciasNamesAsStringArray(){
		if (provincias.isEmpty())
			loadProvincias();
		
		Iterator iter = provincias.values().iterator();
		ArrayList<String> provs = new ArrayList<String>();
		while (iter.hasNext()) {
			Provincia p = (Provincia) iter.next();
			provs.add(p.getName());
		}
		return provs.toArray(new String[0]);	
	}

	public Provincia getProvinciaByID(int int1) {
		if (provincias.isEmpty())
			loadProvincias();
		return provincias.get(new Integer(int1));
	}

}
